from django.http import HttpResponse
from django.shortcuts import render
from .models import News, Category, Comment
from django.conf import settings
from django.core import serializers
from utils import restful
from django.http import Http404
from .forms import PublicCommentForm
# 只支持页面跳转，不支持ajax请求
from django.contrib.auth.decorators import login_required
from apps.xfzauth.decorators import xfz_login_required
from django.db.models import Q


def index(request):
    count = settings.ONE_PAGE_NEWS_COUNT
    newses = News.objects.all().order_by("-pub_time")[0:count]
    categories = Category.objects.all()
    return render(request, "index.html", context={"newses": newses, "categories": categories})


def news_list(request):
    # page = int(request.POST.get('p', 1))
    # start = (page-1) * settings.ONE_PAGE_NEWS_COUNT
    # end = start + settings.ONE_PAGE_NEWS_COUNT
    # # newses = News.objects.all().order_by("-pub_time")[start:end].values()
    newses = News.objects.all().order_by("-pub_time")
    # a = serializers.serialize('json', newses)
    categories = Category.objects.all()
    # print(restful.result(data=a))
    return render(request, 'index.html', context={"newses": newses, "categories": categories, "display": "1"})


def news_detail(request, news_id):
    try:
        news = News.objects.get(pk=news_id)
        comments = Comment.objects.filter(news=news)
        context = {
            "news": news,
            "comments": comments
        }
        return render(request, "news_detail.html", context=context)
    except:
        raise Http404


def search(request):
    q = request.GET.get("q")
    context = {}
    if q:
        newses = News.objects.filter(Q(title__contains=q)|Q(content__contains=q))
        context['newses'] = newses
    return render(request, "search.html", context=context)



@xfz_login_required
def add_comment(request):
    form = PublicCommentForm(request.POST)
    if form.is_valid():
        news_id = form.cleaned_data.get('news_id')
        content = form.cleaned_data.get('content')
        news = News.objects.get(pk=news_id)
        comment = Comment.objects.create(content=content, author=request.user, news=news)
        return restful.ok()
    else:
        return restful.params_error(message="评论失败！")

